<?php

/**
 * 后台栏目管理model操作
 * @author  xiaobai
 * @date    2017-01-08
 */

namespace app\common\model;

use app\common\model\Common;
use util\Trees;

class Column extends Common
{
    
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime'; // 自动写入时间，格式为Y-m-d H:i:s

    const TYPE_ARTICLE = 1;
    const TYPE_PAGE    = 2;
    const TYPE_COLUMN  = 3;

    public static $types = array(
        self::TYPE_ARTICLE => '普通文章',
        self::TYPE_PAGE    => '单页',
        self::TYPE_COLUMN  => '栏目首页',
    );

    public function setContentAttr($value)
    {
        $value = !empty($value) ? htmlspecialchars($value) : '';
        return $value;
    }

    /**
     * 下拉菜单，树形
     * @return array|void
     */
    public function selectColumn($parentid = 0, $where = array(), $order = 'sort asc, id desc')
    {
        $result = $this->where($where)->order($order)->select();
        if (empty($result)) {
            return [];
        }
        $result   = $result->toArray();
        $tree     = new Trees($result, 'parentid');
        $res_data = $tree->get_tree($parentid);

        return $res_data;
    }

    /**
     * 获取栏目信息
     * @param int $column_id    栏目id
     * @param int $cache_time   缓存时间，默认2个小时
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getColumnInfo($column_id = 0, $cache_time = 7200)
    {
        $where = array('id'=>$column_id);
        $key   = 'getColumnInfo_'.$column_id;
        $info  = cache($key);
        if (empty($list)) {
            $info = $this->where($where)->find();
            if (!empty($info)) {
                cache($key, $info, $cache_time);
            } else {
                $info = array();
            }
        }
        return $info;
    }

    /**
     * 获取栏目导航栏信息
     * @return array
     */
    public function getColumnNavBar()
    {
        $key = 'getColumnNavBar';
        $column_lists = cache($key);
        if (empty($column_lists)) {
            $column_list  = $this->where(array('display'=>1))->order('sort asc, id desc')->select();
            $column_list  = json_decode(json_encode($column_list),true);
            $column_lists = array();
            foreach ($column_list as $key=>$val) {
                $column_lists[$val['id']] = $val;
            }
            if (!empty($column_lists)) {
                cache($key, $column_lists, 3600*24*7);
            }
        }

        return $column_lists;
    }

    /**
     * 获取栏目以id为key值的列表
     * @return array|mixed
     */
    public function getColumnIdKeyList()
    {
        $key  = 'getColumnIdKeyList';
        $list = cache($key);
        if (empty($list)) {
            $list = $this->order('id desc')->column('name', 'id');
            if (!empty($list)) {
                cache($key, $list, 3600*24*7);
            } else {
                $list = [];
            }
        }

        return $list;
    }
}
